package com.light.component;

import com.light.model.GitProject;
import com.light.thread.FxAsyncTask;
import com.light.util.H2PoolUtils;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.layout.HBox;
import javafx.util.Callback;
import org.kordamp.ikonli.antdesignicons.AntDesignIconsOutlined;
import org.kordamp.ikonli.javafx.FontIcon;

/**
 * 学习等级列 - 星级
 */
public class LevelTableCell extends TableCell<GitProject, Integer> {

    private final HBox hBox = new HBox();

    private final ObservableList<Integer> stars = FXCollections.observableArrayList(0, 1, 2, 3, 4, 5);

    private ChoiceBox<Integer> choiceBox;

    public static Callback<TableColumn<GitProject, Integer>, TableCell<GitProject, Integer>> forTableColumn() {
        return param -> new LevelTableCell();
    }

    public LevelTableCell() {
        hBox.setAlignment(Pos.CENTER_LEFT);
    }

    @Override
    protected void updateItem(Integer item, boolean empty) {
        super.updateItem(item, empty);
        if (empty || item == null || getTableRow() == null) {
            setGraphic(null);
        } else {
            hBox.getChildren().clear();
            for (int i = 0; i < item; i++) {
                hBox.getChildren().add(new FontIcon(AntDesignIconsOutlined.STAR));
            }
            setGraphic(hBox);
        }
    }

    @Override
    public void startEdit() {
        super.startEdit();
        if (!isEditing()) {
            return;
        }
        int oldValue = getItem();
        if (choiceBox == null) {
            choiceBox = new ChoiceBox<>(stars);
            choiceBox.setMaxWidth(Double.MAX_VALUE);
            choiceBox.showingProperty().addListener(event -> {
                if (!choiceBox.isShowing()) {
                    commitEdit(choiceBox.getValue());
                    if (oldValue != choiceBox.getValue()) {
                        FxAsyncTask.runOnce("更新学习等级", () -> H2PoolUtils.updateGitProject(getTableRow().getItem()));
                    }
                }
            });
        }

        choiceBox.getSelectionModel().select(getItem());
        setText(null);
        setGraphic(choiceBox);
    }

    @Override
    public void commitEdit(Integer newValue) {
        super.commitEdit(newValue);
    }

    @Override
    public void cancelEdit() {
        super.cancelEdit();
        hBox.getChildren().clear();
        for (int i = 0; i < getItem(); i++) {
            hBox.getChildren().add(new FontIcon(AntDesignIconsOutlined.STAR));
        }
        setGraphic(hBox);
    }
}
